package com.mainbo.modular.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.ClassUserMessage;
import com.mainbo.modular.jms.model.PeopleStudentMessageVo;
import com.mainbo.modular.jms.model.PeopleStudentVo;
import com.mainbo.modular.system.dao.PtClassUserMapper;
import com.mainbo.modular.system.model.PtClassUser;
import com.mainbo.modular.system.model.PtPeopleStudent;
import com.mainbo.modular.system.model.Student;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.service.IPtClassUserService;
import com.mainbo.modular.system.service.IPtPeopleStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生变更机构
 * @author moshang
 * @date 2020-03-02
 **/
@Component
public class StudentListener implements Listener {

    private static final Logger logger = LoggerFactory.getLogger(StudentListener.class);

    public static final String EVENT_UPDATE_USER_ORG = "event_update_user_org";

    @Autowired
    private JmsService jmsService;
    @Autowired
    private IPtClassUserService classUserService;
    @Autowired
    private IPtPeopleStudentService peopleStudentService;
    @Resource
    private PtClassUserMapper classUserMapper;

    @SuppressWarnings("unchecked")
    @Override
    public void lifecycleEvent(ListenableEvent event) {
        if (EVENT_UPDATE_USER_ORG.equals(event.getType())) {
            if (event.getData() instanceof Map) {
                HashMap<String, Object> data = (HashMap<String, Object>) event.getData();
                Student oldStu = (Student) data.get("oldStu");
                String newOrgId = (String) data.get("newOrgId");
                PtClassUser cu = new PtClassUser();
                cu.setOrgId(oldStu.getOrgId());
                cu.setUserId(oldStu.getId());
                cu.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(oldStu.getOrgId()));
                cu.setType(PtClassUser.TYPE_STUDENT);
                PtClassUser one = classUserMapper.selectOne(cu);
                if (one != null) {
                    classUserService.deleteById(one.getId());
                    //LoggerUtils.deleteLogger(LoggerModule.ORGMANAGE, "组织结构管理——班级管理——删除班级和学生对应关系，ID:{}", one.getId());
                    // 发送消息
                    ClassUserMessage classUserVo = new ClassUserMessage();
                    try {
                        BeanUtils.copyProperties(one, classUserVo);
                        classUserVo.setMessageType(MessageTypes.CLASS_STUDENT_DELETE.name());
                        jmsService.sendMessage(classUserVo);
                    } catch (Exception e) {
                        logger.error("组织机构管理——班级管理——发送‘删除班级和学生对应关系’消息失败", e);
                    }
                }
                EntityWrapper<PtPeopleStudent> oldps = new EntityWrapper<>();
                oldps.eq("org_id",oldStu.getOrgId());
                oldps.eq("student_id",oldStu.getId());
                List<PtPeopleStudent> allps = peopleStudentService.selectList(oldps);
                for (PtPeopleStudent peopleStudent : allps) {
                    peopleStudent.setOrgId(newOrgId);
                    peopleStudentService.updateById(peopleStudent);
                    this.sendMessage(MessageTypes.PEOPLE_STUDENT_UPDATE, peopleStudentService.selectById(peopleStudent.getId()));
                }
            }
        }
    }

    public void sendMessage(MessageTypes type, PtPeopleStudent ps) {
        try {
            PeopleStudentMessageVo vo = new PeopleStudentMessageVo();
            vo.setMessageType(type.name());
            PeopleStudentVo peopleStudentVo = new PeopleStudentVo();
            BeanUtils.copyProperties(ps, peopleStudentVo);
            vo.setPeopleStudentVo(peopleStudentVo);
            jmsService.sendMessage(vo);
        } catch (Exception e) {
            logger.error("发送消息失败，消息类型{},异常{}", type.name(), e);
        }

    }

    @Override
    public boolean supports(Object[] supportsType) {
        boolean supports = false;
        if (supportsType != null) {
            for (Object o : supportsType) {
                if (EVENT_UPDATE_USER_ORG.equals(o)) {
                    supports = true;
                    break;
                }
            }
        }
        return supports;
    }

}
